import react from "@vitejs/plugin-react";
import { resolve } from "path";
import { defineConfig } from "vite";
import vitePluginCompression from "vite-plugin-compression";
import eslintPlugin from "vite-plugin-eslint";
import { viteMockServe } from "vite-plugin-mock";

// const baseUrl = "web";

const proxy = {
  dev: {
    "/api": {
      target: "http://192.168.10.231:14431/dom-mdm",
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/api/, ""),
    },
    "/auth": {
      target: "http://192.168.10.231:14431/authserver",
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/auth/, ""),
    },
    "/manager": {
      target: "http://192.168.10.209:4431/manager",
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/manager/, ""),
    },
  },
};

export default defineConfig((config) => {
  // const { command, mode } = config;
  console.log("[vite config] run: ", config);

  return {
    plugins: [
      react({
        jsxImportSource: "@emotion/react",
        babel: {
          plugins: [
            [
              "@emotion/babel-plugin",
              {
                autoLabel: "always",
                labelFormat: "webapp-[local]",
                cssPropOptimization: true,
              },
            ],
          ],
        },
      }),
      viteMockServe({
        mockPath: "mock",
        watchFiles: false,
        enable: true,
        logger: true,
      }),
      eslintPlugin({
        emitWarning: false,
      }),
      vitePluginCompression({
        threshold: 1024 * 10, // 对大于 10kb 的文件进行压缩
        // deleteOriginFile: true,
      }),
    ],
    define: {
      // 解决 vite 找不到 process.env 环境变量
      "process.env": {},
    },
    resolve: {
      alias: {
        "@": `${resolve(process.cwd(), "src")}`,
      },
    },
    server: {
      open: true,
      port: 5794,
      host: "0.0.0.0",
      proxy: proxy["dev"],
    },
    // or use ./
    // base: config.mode === "development" ? "/" : `/${baseUrl}/`,
    // base: `/${baseUrl}/`,
    base: "./",
    build: {
      sourcemap: false,
      outDir: "dist",
      rollupOptions: {
        output: {
          chunkFileNames: "js/[name]-[hash].js", // 引入文件名的名称
          entryFileNames: "js/[name]-[hash].js", // 包的入口文件名称
          assetFileNames: "[ext]/[name]-[hash].[ext]", // 资源文件像 字体，图片等
          manualChunks(id) {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
    },
  };
});
